home *** CD-ROM | disk | FTP | other *** search
/ Super PC 34 / Super PC 34 (Shareware).iso / spc / UTIL / DJGPP2 / V2 / DJLSR200.ZIP / src / libc / compat / stdlib / putenv.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-01-25  |  2.0 KB  |  94 lines

  1. /* Copyright (C) 1996 DJ Delorie, see COPYING.DJ for details */
  2. /* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */
  3. #include <libc/stubs.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <libc/bss.h>
  7.  
  8. /*
  9.  
  10.    This routine assumes that the environ array and all strings it
  11.    points to were malloc'd.  Nobody else should modify the environment
  12.    except crt1.c
  13.  
  14. */
  15.  
  16. extern char **environ;
  17. static int ecount = -1;
  18. static int emax = -1;
  19. static int putenv_bss_count = -1;
  20.  
  21. int
  22. putenv(const char *val)
  23. {
  24.   int vlen = strlen(val);
  25.   char *epos = strchr(val, '=');
  26.   int nlen = epos - val + 1;
  27.   int eindex;
  28.  
  29.   if (epos == 0)
  30.     return -1;
  31.  
  32.   if (putenv_bss_count != __bss_count)
  33.   {
  34.     putenv_bss_count = __bss_count;
  35.     for (ecount=0; environ[ecount]; ecount++);
  36.     emax = ecount;
  37.   }
  38.  
  39.   for (eindex=0; environ[eindex]; eindex++)
  40.     if (strncmp(environ[eindex], val, nlen) == 0)
  41.     {
  42.       char *oval = environ[eindex];
  43.  
  44.       if (val[nlen] == 0) /* delete the entry */
  45.       {
  46.     free(oval);
  47.     environ[eindex] = environ[ecount-1];
  48.     environ[ecount-1] = 0;
  49.     ecount--;
  50.     return 0;
  51.       }
  52.  
  53.       /* change existing entry */
  54.       if (strcmp(environ[eindex]+nlen, val+nlen) == 0)
  55.     return 0; /* they're the same */
  56.       environ[eindex] = (char *)malloc(vlen+1);
  57.       if (environ[eindex] == 0)
  58.       {
  59.     environ[eindex] = oval;
  60.     return -1;
  61.       }
  62.       free(oval);
  63.       strcpy(environ[eindex], val);
  64.       return 0;
  65.     }
  66.  
  67.   /* delete nonexisting entry? */
  68.   if (val[nlen] == 0)
  69.     return 0;
  70.  
  71.   /* create new entry */
  72.   if (ecount >= emax)
  73.   {
  74.     char **enew;
  75.     emax += 10;
  76.     enew = (char **)malloc(emax * sizeof(char **));
  77.     if (enew == 0)
  78.       return -1;
  79.     memcpy(enew, environ, ecount * sizeof(char *));
  80.     free(environ);
  81.     environ = enew;
  82.   }
  83.  
  84.   environ[ecount] = (char *)malloc(vlen+1);
  85.   if (environ[ecount] == 0)
  86.     return -1;
  87.   strcpy(environ[ecount], val);
  88.  
  89.   ecount++;
  90.   environ[ecount] = 0;
  91.  
  92.   return 0;
  93. }
  94.